package com.seadragon.app.ksr.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.MatrixVariable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.seadragon.app.ksr.dao.CategoryDao;
import com.seadragon.app.ksr.model.Business;
import com.seadragon.app.ksr.model.Category;
import com.seadragon.app.ksr.model.KsrConstants;
import com.seadragon.app.ksr.model.Office;
import com.seadragon.app.ksr.service.BusinessService;
import com.seadragon.app.ksr.service.OfficeService;
import com.seadragon.app.ksr.util.CacheManager;
import com.seadragon.app.ksr.util.GsonUtils;

@Controller
public class BusinessAndOfficeController {
	private static Logger logger = LoggerFactory.getLogger(BusinessAndOfficeController.class);

	@Autowired
	private BusinessService businessService;
	
	@Autowired
	private OfficeService officeService;
	
	@Autowired
	private CacheManager cacheManager;
	
	@Autowired
	private CategoryDao categoryDao;


	@RequestMapping(value = "/business/category/list.json", method = RequestMethod.GET)
	public @ResponseBody
	String getCategoryListJson(HttpServletRequest request, HttpSession session) {
		List<Category> list = categoryDao.findAllByLevel(1);
		String json = GsonUtils.ObjectToGson(list, "category");
		return json;
	}
	
	
	
	@RequestMapping(value = {"/business/profile/get.json"}, method = RequestMethod.GET)
	public @ResponseBody
	String getBusinessProfileJson(HttpServletRequest request, HttpSession session) {
		String json = null;
		if (session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS) != null) {
			Business business = (Business )session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS);
			json = GsonUtils.ObjectToGson(business);
		}
		return json;
	}	
	
	
	@RequestMapping(value = {"/business/profile/{id}/get.json"}, method = RequestMethod.GET)
	public @ResponseBody
	String getBusinessProfileJsonById(HttpServletRequest request, HttpSession session,@PathVariable int id) {
		String json = null;
		Business business = businessService.findById(id);
		if (business != null) {
			json = GsonUtils.ObjectToGson(business);
		}
		return json;
	}	

	//update or create a business
	@RequestMapping(value = "/business/profile/save.json", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject saveBusinessProfile(@RequestBody String json,HttpSession session) {
		logger.debug(json);
		Business business = (Business)GsonUtils.GsonToObject(json, Business.class);
				
		//rebuild the categories set because they all miss the parents
		for (Category category : business.getCategories()) {
			if (category.getId()>0) {
				for (Category categ : cacheManager.getAllLeafCatogories()) {
					if (categ.getId() == category.getId()) {
						BeanUtils.copyProperties(categ, category);
						break;
					}
				}
			}
		}
		if (business.getId()>0)
			businessService.update(business);
		else
			businessService.save(business);
		
		session.setAttribute(KsrConstants.SESSION_SCOPED_BUSINESS, business);
		
		JSONObject data = new JSONObject();
		data.put("status", "ok");
	return data;
}
	

	@RequestMapping(value = "/business/office/list/{rating}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeListJson1(HttpServletRequest request, HttpSession session,@PathVariable Integer rating) {
		return OfficeListJson((Business)session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS), rating, null, null);
	}
	
	@RequestMapping(value = "/business/office/list/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeListJson2(HttpServletRequest request, HttpSession session,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return OfficeListJson((Business)session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS), null, offset, pagesize);
	}
	
	@RequestMapping(value = "/business/office/list/{rating}/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeListJson3(HttpServletRequest request, HttpSession session,@PathVariable Integer rating,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return OfficeListJson((Business)session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS), rating, offset, pagesize);
	}
	
	@RequestMapping(value = "/business/office/list.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeListJson(HttpServletRequest request, HttpSession session) {
		return OfficeListJson((Business)session.getAttribute(KsrConstants.SESSION_SCOPED_BUSINESS), null, null, null);
	}
	
	
	@RequestMapping(value = "/business/office/{businessId}/list/{rating}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeListJson4(HttpServletRequest request, HttpSession session,@PathVariable int businessId,@PathVariable Integer rating) {
		return OfficeListJson(businessService.findById(businessId), rating, null, null);
	}
	
	@RequestMapping(value = "/business/office/{businessId}/list/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeListJson5(HttpServletRequest request, HttpSession session,@PathVariable int businessId,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return OfficeListJson(businessService.findById(businessId), null, offset, pagesize);
	}
	
	@RequestMapping(value = "/business/office/{businessId}/list/{rating}/{offset}/{pagesize}.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeListJson6(HttpServletRequest request, HttpSession session,@PathVariable int businessId,@PathVariable Integer rating,@PathVariable Integer offset,@PathVariable Integer pagesize) {
		return OfficeListJson(businessService.findById(businessId), rating, offset, pagesize);
	}	
	//get office list
	@RequestMapping(value = "/business/office/{businessId}/list.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeListJsonByBusiness(HttpServletRequest request, HttpSession session,@PathVariable int businessId) {
		return OfficeListJson(businessService.findById(businessId), null, null, null);
	}
	
	
	private String OfficeListJson (Business business,Integer rating,Integer offset,Integer pagesize){
		String json = null;
		List<Office> offices = null;
		if (business != null) {
			offices = officeService.findAllBy(business);
		} else if (offset!=null&&pagesize!=null) {
			offices = officeService.findAll(offset.intValue(), pagesize.intValue());
		}
		if (offices!=null)
			json =GsonUtils.ObjectToGson(offices);
		return json;
	}
	
	@RequestMapping(value = "/business/office/{id}/get.json", method = RequestMethod.GET)
	public @ResponseBody
	String getOfficeJsonById(HttpServletRequest request, HttpSession session,@PathVariable long id) {
		String json = null;
		Office office = officeService.findById(id);
		if (office!=null)
			json =GsonUtils.ObjectToGson(office);
		return json;
	}
	
	
	//todo: need to check if the user is logged in and if the office belong to the business
	@RequestMapping(value = "/business/office/{id}/remove.json", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject removeOfficeById(HttpServletRequest request, HttpSession session,@PathVariable long id) {
		JSONObject json = new JSONObject();
		try {
			if (officeService.remove(id)){
				json.put("status", "success");
			} else {
				json.put("status", "fail");
			}
			
		} catch (Exception e) {
			json.put("status", "fail");
			json.put("error", e.getMessage());
		}
		return json;
	}	
	
	@RequestMapping(value = "/business/office/save.json", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject createOffice(@RequestBody String officeJson,HttpSession session) {
		logger.debug(officeJson);
		Office office = (Office)GsonUtils.GsonToObject(officeJson, Office.class);
		// save office
		if (office.getId()>0)
			officeService.update(office);
		else
			officeService.save(office);
		
		JSONObject json = new JSONObject();
		json.put("status", "ok");
		return json;
	}
}
